package com.springboot.tools.filter;

import java.io.IOException;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class LoginFilter implements Filter {
    private FilterConfig conf;

    public void destroy() {

    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        String charset = conf.getInitParameter("charset");
        if (null == charset) {
            charset = "UTF-8";
        }
        request.setCharacterEncoding(charset);
        HttpSession sessiom = request.getSession();
        String noLoginPath = conf.getInitParameter("noLoginPath");
        if (noLoginPath != null) {
            String path[] = noLoginPath.split(";");
            for (int i = 0; i < path.length; i++) {
                if (path[i] == null || "".equals(path[i])) continue;
                if (request.getRequestURI().indexOf(path[i]) != -1) {
                    arg2.doFilter(request, response);
                    return;
                }
            }
        }

        if (sessiom.getAttribute("username") != null) {
            arg2.doFilter(request, response);
        } else {
            response.sendRedirect("login.jsp");
        }
    }

    @Override
    public void init(FilterConfig arg0) {
        conf = arg0;
    }
}
